#include "capturepacket.h"
#include <QDebug>
#include <QStringList>

CapturePacket::CapturePacket(QObject *parent):QObject(parent) {}

void CapturePacket::showDeviceName(){
    char errorContent[PCAP_ERRBUF_SIZE];
    pcap_if_t *allDevs;
    QStringList interfaceList;
    if(pcap_findalldevs(&allDevs,errorContent)==-1){
        fprintf(stderr,"failure when find devs: %s\n",errorContent);
        emit interfacesFound(QStringList());
        return;
    }

    for(pcap_if_t *dev = allDevs;dev!=nullptr;dev = dev->next){
        interfaceList.append(QString::fromLocal8Bit(dev->name));
        qDebug()<<dev->name;
    }

    emit interfacesFound(interfaceList);
}

void CapturePacket::capturePacket(QString time,QString from,QString to,
                                  QString length,QString information){
    packetTime = time;
    packetFrom = from;
    packetTo = to;
    packetLength = length;
    packetInformation = information;

    emit packetCaptured();
}

void CapturePacket::startCapture(const QString& context){
    if(myPacket){
        stopCapture();
    }
    myPacket = new MyPacket(context);

    // 连接信号，将抓包数据传递到主线程
    connect(myPacket,&MyPacket::captured,this,&CapturePacket::packetCaptured);

    // 启动线程
    myPacket->start();
}

void CapturePacket::stopCapture(){
    if(myPacket){
        myPacket->stop();
        myPacket->wait();
        delete myPacket;
        myPacket = nullptr;
    }
}
